package server;

import common.LogUtil;
import common.ProxyMapping;

import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * 代理服务管理
 */
public class ProxyManager {
    private static final Logger logger = LogUtil.getLogger(ProxyManager.class.getName());

    // 关联的代理服务器
    private final ProxyServer server;

    // 代理服务映射
    private final Map<String, ProxyService> proxyServices = new ConcurrentHashMap<>();

    // 用户连接映射
    private final Map<Integer, UserConnection> userConnections = new ConcurrentHashMap<>();

    // 连接ID生成器
    private int nextConnectionId = 1;

    /**
     * 构造函数
     */
    public ProxyManager(ProxyServer server) {
        this.server = server;
    }

    /**
     * 添加代理服务
     */
    public void addProxyService(ProxyMapping mapping) throws IOException {
        String name = mapping.getName();
        if (proxyServices.containsKey(name)) {
            logger.warning("Proxy service already exists: " + name);
            return;
        }

        // 创建代理服务
        ProxyService service = new ProxyService(this, mapping);
        proxyServices.put(name, service);

        // 启动代理服务
        service.start();

        logger.info("Proxy service added: " + name + " on port " + mapping.getListenPort());
    }

    /**
     * 移除代理服务
     */
    public void removeProxyService(String name) {
        ProxyService service = proxyServices.remove(name);
        if (service != null) {
            service.stop();
            logger.info("Proxy service removed: " + name);
        }
    }

    /**
     * 获取代理服务
     */
    public ProxyService getProxyService(String name) {
        return proxyServices.get(name);
    }

    /**
     * 创建新用户连接
     */
    public UserConnection createUserConnection(ProxyService service, SocketChannel userChannel) {
        // 生成连接ID
        int connectionId = getNextConnectionId();

        // 创建用户连接
        UserConnection connection = new UserConnection(this, service, connectionId, userChannel);
        userConnections.put(connectionId, connection);

        logger.info("User connection created: " + connectionId);

        return connection;
    }

    /**
     * 移除用户连接
     */
    public void removeUserConnection(int connectionId) {
        UserConnection connection = userConnections.remove(connectionId);
        if (connection != null) {
            connection.close();
            logger.info("User connection removed: " + connectionId);
        }
    }

    /**
     * 获取用户连接
     */
    public UserConnection getUserConnection(int connectionId) {
        return userConnections.get(connectionId);
    }

    /**
     * 获取下一个连接ID
     */
    private synchronized int getNextConnectionId() {
        return nextConnectionId++;
    }

    /**
     * 获取连接数量
     */
    public int getConnectionCount() {
        return userConnections.size();
    }

    /**
     * 关闭所有代理服务
     */
    public void closeAll() {
        // 关闭所有用户连接
        for (UserConnection connection : userConnections.values()) {
            connection.close();
        }
        userConnections.clear();

        // 关闭所有代理服务
        for (ProxyService service : proxyServices.values()) {
            service.stop();
        }
        proxyServices.clear();
    }

    /**
     * 获取代理服务器
     */
    public ProxyServer getServer() {
        return server;
    }
}
